package net.lab1024.sa.admin.module.yitihua;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class YiController {

    @NoNeedLogin
    @RequestMapping("/rest/client/token.do")
    public String token(@RequestBody(required = false) String rawJson, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new  JSONObject();
        jsonObject.put("returnCode", "0");
        jsonObject.put("token", "qpxJOiDb95UtvroVx2Nv0wuerCb1ub4LsOovdYtGHT4=");
        return jsonObject.toJSONString();
    }

    @NoNeedLogin
    @RequestMapping("/rest/open/microService.do")
    public String microService(@RequestBody(required = false) String rawJson, HttpServletRequest request) throws InterruptedException {
        Thread.sleep(500);
        String requestURI = request.getRequestURI();
        log.info("requestURI:{}", requestURI);
        String method = request.getMethod();
        log.info("method:{}", method);
        String queryString = request.getQueryString();
        log.info("queryString:{}", queryString);
        //获得请求体
        log.info("rawJson:{}", rawJson);
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("parameterMap:{}", parameterMap);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("headerName:{}", headerName);
            log.info("header:{}", request.getHeader(headerName));
        }
        String jsonString = JSONObject.toJSONString(log);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        jsonObject.put("returnCode", "0");
        return jsonObject.toJSONString();
    }

    @Value("${integration.event.url:http://111.206.218.229/xfjgfw-xfjg}")
    private String URL;
    @Value("${integration.event.bjxfappId:22041288f3673e35b73a20e8b0c9b030}")
    private String bjxfappId;
    @Value("${integration.event.rsign:367y0k37r3094725}")
    private String rsign;
    // 缓存的token
    private String cachedToken;
    // token的获取时间
    private long tokenFetchTime;
    // token有效期，单位：毫秒
    private static final long TOKEN_EXPIRATION_TIME = 30 * 60 * 1000;

    private String getToken(String bjxfrtime) throws Exception {
        // 检查缓存的token是否有效
        if (cachedToken != null && System.currentTimeMillis() - tokenFetchTime < TOKEN_EXPIRATION_TIME) {
            log.info("一体化平台--使用缓存的token");
            return cachedToken;
        }
        JSONObject header = new JSONObject();
        header.put("bjxfappId", bjxfappId);
        header.put("bjxfrtime", bjxfrtime);
        header.put("bjxfrsign", SM4Utils.encryptData_ECB(String.valueOf(bjxfrtime), rsign));
        JSONObject result = null;
        result = HttpUtil.httpGet(URL + "/rest/client/token.do", header);
        String token = null;
        if (result.getInteger("responseCode") == 200) {
            JSONObject data = JSONObject.parseObject(result.getString("responseString"));
            if ("0".equals(data.getString("returnCode"))) {
                token = SM4Utils.decryptData_ECB(data.getString("token"), rsign);
                // 缓存新的token和获取时间
                cachedToken = token;
                tokenFetchTime = System.currentTimeMillis();
            }
        }
        System.out.println("一体化平台--获取token:"+token);
        return token;
    }

    public static void main1(String[] args) throws Exception {
        String bjxfrtime = String.valueOf(System.currentTimeMillis());

        // 检查缓存的token是否有效
        JSONObject header = new JSONObject();
        header.put("bjxfappId", "22041288f3673e35b73a20e8b0c9b030");
        header.put("bjxfrtime", bjxfrtime);
        header.put("bjxfrsign", SM4Utils.encryptData_ECB(String.valueOf(bjxfrtime), "367y0k37r3094725"));
        JSONObject result = null;
        result = HttpUtil.httpGet("http://111.206.218.229/xfjgfw-xfjg" + "/rest/client/token.do", header);
        String token = null;
        if (result.getInteger("responseCode") == 200) {
            JSONObject data = JSONObject.parseObject(result.getString("responseString"));
            if ("0".equals(data.getString("returnCode"))) {
                token = SM4Utils.decryptData_ECB(data.getString("token"), "367y0k37r3094725");
                // 缓存新的token和获取时间
            }
        }
        //String token = "b24dac5b8032733e";
        System.out.println("一体化平台--获取token:"+token);

        //JSONObject jsonObject = null;
        try {
            String ttt = String.valueOf(System.currentTimeMillis());
            HttpHeaders headers = new HttpHeaders();

            headers.add("bjxfappId", "22041288f3673e35b73a20e8b0c9b030");
            headers.add("bjxfrtime",ttt );
            headers.add("bjxfrsign", SM4Utils.encryptData_ECB(ttt, token));
            headers.add("Content-Type", "application/json");
            //jsonObject = HttpUtil.httpGet(url, header1);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("start", 1);
            jsonObject.put("pageSize", 10);
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            // 1. 创建 CookieManager
            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); // 接受所有 Cookie
            // 2. 将 CookieManager 包装成 OkHttp 的 CookieJar
            JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
            OkHttpClient client = new OkHttpClient.Builder()
                    .cookieJar(cookieJar)
                    .followRedirects(true)
                    .followSslRedirects(true)
                    .addInterceptor(logging)
                    .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                    .readTimeout(30, TimeUnit.SECONDS)     // 读取超时（服务器响应太慢）
                    .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时（发送请求体太慢，如大文件上传）
                    .callTimeout(60, TimeUnit.SECONDS)     // 总调用超时（从开始到结束）
                    .build();

            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            String json = "{\"start\": \"1\", \"pageSize\": \"10\"}";

            Request request = new Request.Builder()
                    .url("http://xfzhjg.bj.119.gov.cn/xfjgfw-xfjg" + "/rest/open/microService.do?serviceCode=XF-DICT-GET-COMPOUND")
                    .post(okhttp3.RequestBody.create(json, JSON))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Host", "xfzhjg.bj.119.gov.cn")
                    .addHeader("bjxfappId", "22041288f3673e35b73a20e8b0c9b030")
                    .addHeader("bjxfrtime", ttt)
                    .addHeader("bjxfrsign", SM4Utils.encryptData_ECB(ttt, token))
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    System.out.println("Response: " + response.body().string());
                } else {
                    System.out.println("Error: " + response.code());
                }
            }

            //String post = RestTemplateUtil.postRS(headers,  "http://111.206.218.229/xfjgfw-xfjg" + "/rest/open/microService.do?serviceCode=XF-ZDGARQ-HOUSE-LIST", jsonObject);
            //System.out.println("post:"+post);
            /*if (post != null && "0".equals(post.getString("returnCode"))) {
                String str = post.getString("data");
                System.out.println("str:"+str);
            }*/
            /*jsonObject = JSONObject.parseObject(jsonObject.getString("responseString"));
            String str = jsonObject.getString("data");
            System.out.println(str);
            String data = base64decode(str.getBytes()); // base64解密
            data = aesDecrypt(data, "367y0k37r3094725"); // aes解密，参数里面填写由平台为您分配的AES加解密Key
            JSONObject jsonObject1 = JSONObject.parseObject(data);
            String rows = jsonObject1.getString("rows");*/
        } catch (Exception e) {
            log.error("一体化平台--获取listData失败:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }


    public static void main11(String[] args) throws Exception {
        /*String bjxfrtime = String.valueOf(System.currentTimeMillis());

        // 检查缓存的token是否有效
        JSONObject header = new JSONObject();
        header.put("bjxfappId", "22041288f3673e35b73a20e8b0c9b030");
        header.put("bjxfrtime", bjxfrtime);
        header.put("bjxfrsign", SM4Utils.encryptData_ECB(String.valueOf(bjxfrtime), "367y0k37r3094725"));
        JSONObject result = null;
        result = HttpUtil.httpGet("http://111.206.218.229/xfjgfw-xfjg" + "/rest/client/token.do", header);
        String token = null;
        if (result.getInteger("responseCode") == 200) {
            JSONObject data = JSONObject.parseObject(result.getString("responseString"));
            if ("0".equals(data.getString("returnCode"))) {
                token = SM4Utils.decryptData_ECB(data.getString("token"), "367y0k37r3094725");
                // 缓存新的token和获取时间
            }
        }*/
        String token = "aeaf9ba5243e5263";
        System.out.println("一体化平台--获取token:"+token);
        System.out.println("header:"+token);
        //JSONObject jsonObject = null;
        try {
            String ttt = String.valueOf(System.currentTimeMillis());
            HttpHeaders headers = new HttpHeaders();
            headers.add("bjxfappId", "22041288f3673e35b73a20e8b0c9b030");
            headers.add("bjxfrtime",ttt );
            headers.add("bjxfrsign", SM4Utils.encryptData_ECB(ttt, token));
            headers.add("Content-Type", "application/json");
            System.out.println("headers:"+headers);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("start", 1);
            jsonObject.put("pageSize", 50);
            String post = RestTemplateUtil.postRS(headers,  "http://xfzhjg.bj.119.gov.cn/xfjgfw-xfjg" + "/rest/open/microService.do?serviceCode=XF-DICT-GET-COMMUNITY", jsonObject);
            System.out.println("post:"+post);
            /*if (post != null && "0".equals(post.getString("returnCode"))) {
                String str = post.getString("data");
                System.out.println("str:"+str);
            }*/
            /*jsonObject = JSONObject.parseObject(jsonObject.getString("responseString"));
            String str = jsonObject.getString("data");
            System.out.println(str);
            String data = base64decode(str.getBytes()); // base64解密
            data = aesDecrypt(data, "367y0k37r3094725"); // aes解密，参数里面填写由平台为您分配的AES加解密Key
            JSONObject jsonObject1 = JSONObject.parseObject(data);
            String rows = jsonObject1.getString("rows");*/
        } catch (Exception e) {
            log.error("一体化平台--获取listData失败:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        JSONObject result = JSON.parseObject("");
        result.getInteger("start");
    }

    public static String base64decode(final byte[] bytes) {
        return new String(Base64.decodeBase64(bytes), StandardCharsets.UTF_8);
    }

    public static String aesDecrypt(String content, String aesKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(aesKey.getBytes(StandardCharsets.UTF_8));
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] encrypted = Base64.decodeBase64(content);
            byte[] result = cipher.doFinal(encrypted);
            return new String(result, StandardCharsets.UTF_8); // 解密
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |
                 BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

}
